﻿using MediatR;
using ProcurementManagement.Applcation.Command.PricingCommand;
using ProcurementManagement.Domain.ProcurementDomain;
using ProcurementManagement.Infrstructre.Interface;
using SqlSugar;

namespace ProcurementManagement.Applcation.CommandHanlers.PricingCommandHandlers
{
    public class PricingCrteateCommandHandlers : IRequestHandler<PricingCrteateCommand, int>
    {
        protected readonly IPricingRepository pricing;
        protected readonly IProcureEnquiryRepository repository;
        protected readonly ISqlSugarClient db;

        public PricingCrteateCommandHandlers(IPricingRepository pricing, IProcureEnquiryRepository repository, ISqlSugarClient db)
        {
            this.pricing = pricing;
            this.repository = repository;
            this.db = db;
        }

        public async Task<int> Handle(PricingCrteateCommand request, CancellationToken cancellationToken)
        {
            db.Ado.BeginTran();
            try
            {
                PurchasePricing ping = new PurchasePricing();
                ping.ProcureEnquiryId = request.ppdtoo.ProcureEnquiryId;
                ping.IsDel = false;
                ping.AddName = request.ppdtoo.AddName;
                ping.AddTime = DateTime.Now;
                ping.Office_Id = request.ppdtoo.Office_Id;
                ping.User_Id = request.ppdtoo.User_Id;
                await pricing.AddAsync(ping);
                var oldList = (await repository.GetAll()).First(x => x.ProcureEnquiryId == request.ppdtoo.ProcureEnquiryId);
                oldList.IsState = true;
                await repository.UpdataAsync(oldList);

                db.Ado.CommitTran();
                return 1;
            }
            catch (Exception)
            {
                db.Ado.RollbackTran();
                throw;
            }

        }
    }
}
